package com.yundasys.lab08jvm.lock.secskill.impl;

import com.yundasys.lab08jvm.lock.secskill.ISeckillService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jiangta
 * @version 1.0
 * @date 2021/6/11 9:10 上午
 */
@Service("seckillService")
public class SeckillServiceImpl implements ISeckillService {

    private Lock lock = new ReentrantLock(false);

    @Autowired
    private JdbcTemplate jdbcTempalte;

    @Override
    @Transactional
    public String startSeckilLock(long seckillId, long userId) {
        try {
            //lock.lock();
            //这里、不清楚为啥、总是会被超卖101、难道锁不起作用、lock是同一个对象
            String nativeSql = "SELECT number FROM seckill WHERE seckill_id=?";
            Integer number =  jdbcTempalte.queryForObject(nativeSql, new Object[]{seckillId},Integer.class);
            if(number>0){
                nativeSql = "UPDATE seckill  SET number=number-1 WHERE seckill_id=?";
                jdbcTempalte.update(nativeSql,new Object[]{seckillId});
            }else{
                return "error";
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //lock.unlock();
        }
        return "success";
    }
}
